package com.example.demo.controller;
/* @Author      zouzh
 * @PackageName BlogSystem-sm
 * @Package     com.example.demo.model
 * @Date        2023/9/5 13:48
 */


import com.example.demo.common.AppVar;
import com.example.demo.common.ResultAjax;
import com.example.demo.common.SessionUtils;
import com.example.demo.dao.UserMapper;
import com.example.demo.model.ArticleInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.model.vo.UserinfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    private static final int _DESC_LENGTH = 120;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @RequestMapping("/mylist")
    public ResultAjax myList(HttpServletRequest request){
        // 1. 得到当前登录的用户
        UserInfo userInfo = SessionUtils.getUser(request);
        if (userInfo == null){
            return ResultAjax.fail(-1,"请先登录");
        }
        // 2. 根据用户 id 查询此用户发表的所有文章
        List<ArticleInfo> list = articleService.getListByUid(userInfo.getId());
        // 处理 list -> 将文章正文变成简介
        if (list != null && list.size() > 0){
            // 并行处理 list 集合
            list.stream().parallel().forEach((art)->{
                if (art.getContent().length() > _DESC_LENGTH){
                    art.setContent(art.getContent().substring(0, _DESC_LENGTH));
                }
            });
        }
        // 3. 返回给前端
        return ResultAjax.succ(list);
    }

    /**
     * 删除文章
     */
    @RequestMapping("/del")
    public ResultAjax del(Integer aid, HttpServletRequest request){
        // 1.参数校验
        if (aid == null || aid <= 0){
            return ResultAjax.fail(-1,"参数错误");
        }
        // 2.得到当前用户
        UserInfo userInfo = SessionUtils.getUser(request);
        if (userInfo ==null){
            ResultAjax.fail(-1,"请先登录");
        }
        // 3.归属人判断+删除操作
        int result = articleService.delByAid(aid, userInfo.getId());
        // 4.将结果返回给前端
        return ResultAjax.succ(result);
    }

    /**
     * 添加文章
     * @return
     */
    @RequestMapping("/add")
    public ResultAjax add(ArticleInfo articleInfo, HttpServletRequest request){
        // 1.校验参数
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle())
                || !StringUtils.hasLength(articleInfo.getContent())){
            return ResultAjax.fail(-1,"非法参数");
        }
        // 2. 获取用户 组装数据
        UserInfo userInfo = SessionUtils.getUser(request);
        if (userInfo == null){
            return  ResultAjax.fail(-2, "请先登录");
        }
        articleInfo.setUid(userInfo.getId());
        // 3.将数据入库
        int result = articleService.add(articleInfo);
        // 4.将数据返回给前端
        return ResultAjax.succ(result);
    }
    /**
     * 查询自己发表的文章详情
      */
    @RequestMapping("/update_init")
    public ResultAjax updateInit(Integer id, HttpServletRequest request){
        // 1.校验参数
        if (id == null || id<= 0){
            return ResultAjax.fail(-1, "参数错误");
        }
        // 2. 得到当前用户的 id
        UserInfo userInfo = SessionUtils.getUser(request);
        if (userInfo == null){
            return ResultAjax.fail(-2,"请先登录");
        }
        // 3.查询数据
        ArticleInfo articleInfo = articleService.getArticleByIdAndUid(id, userInfo.getId());
       // 4.将结果返回给前端
        return ResultAjax.succ(articleInfo);
    }

    @RequestMapping("/update")
    public ResultAjax update(ArticleInfo articleInfo, HttpServletRequest request){
        // 1.参数检验
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle())
                || !StringUtils.hasLength(articleInfo.getContent())
                || articleInfo.getId() <= 0){
            return ResultAjax.fail(-1, "参数错误");
        }
        // 2. 获取登录用户
        UserInfo userInfo = SessionUtils.getUser(request);
        if (userInfo == null){
            return ResultAjax.fail(-2,"请先登录");
        }
        articleInfo.setUid(userInfo.getId());
        // 3.修改文章并校验归属人
        int result = articleService.update(articleInfo);
        // 4.将结果返回给前端
        return ResultAjax.succ(result);
    }

    /**
     * 查询文章详情页
     */
    @RequestMapping("/detail")
    public ResultAjax detail(Integer aid) throws ExecutionException, InterruptedException {
        // 1. 校验参数
        if (aid == null || aid <= 0){
            return ResultAjax.fail(-1, "参数错误");
        }
        // 2. 查询文章详情
        ArticleInfo articleInfo = articleService.getDetailById(aid);
        if (articleInfo == null){
            return ResultAjax.fail(-1, "参数错误");
        }
        // 3. 根据 uid 查询用户的详情
        FutureTask<UserinfoVO> userTask = new FutureTask<>(() -> {
            return  userService.getUserByid(articleInfo.getUid());
        });
        taskExecutor.submit(userTask);
        // 4. 根据 uid 查询用户发表的总文章数
        FutureTask<Integer> artCountTask = new FutureTask<>( () -> {
            return articleService.getArtCountByUid(articleInfo.getUid());
        });
        taskExecutor.submit(artCountTask);
        // 5. 组装数据，
        UserinfoVO userinfoVO = userTask.get(); // 等待任务（线性池）执行完成
        int artCount = artCountTask.get(); // 等待任务（线性池）执行完成
        userinfoVO.setArtCount(artCount);
        HashMap<String, Object> result = new HashMap<>();;
        result.put("user", userinfoVO);
        result.put("art", articleInfo);
        // 6. 返回结果给前端
        return ResultAjax.succ(result);
    }

    @RequestMapping("/increment_rcount")
    public ResultAjax incrementRCount(Integer aid){
        // 1. 校验参数
        if (aid == null || aid <= 0){
            return ResultAjax.fail(-1, "参数错误");
        }
        // 2. 更改数据库
        int result = articleService.updateRCount(aid);
        // 3. 返回结果
        return ResultAjax.succ(result);
    }

    /***
     * 查询分页功能
     */
    @RequestMapping("/getlistbypage")
     public ResultAjax getListByPage(Integer psize, Integer pindex) throws ExecutionException, InterruptedException {
        // 1.加工参数
        if (pindex == null || pindex <1){
            // 参数矫正
            pindex = 1;
        }
        if (psize == null || psize < 1){
            // 参数矫正
            psize = 2;
        }
        // 2.并发进行文章列表和总页数的查询
        // 2.1 查询分页列表数据
        int offser = psize *(pindex -1); // 分页公式
        Integer finalPsize = psize;
        FutureTask<List<ArticleInfo>> listTask = new FutureTask<>( () -> {
            return articleService.getListByPage( finalPsize, offser);
        });
        // 2.2 查询总页数
        FutureTask<Integer> sizeTask = new FutureTask<>( () -> {
            // 总条数
            int totalCount = articleService.getCount();
            double sizeTemp = (totalCount * 1.0) / (finalPsize * 1.0);
            return (int) Math.ceil(sizeTemp);
        });
        taskExecutor.submit(listTask);
        taskExecutor.submit(sizeTask);
        // 3.组装数据
        List<ArticleInfo> list = listTask.get();
        int size = sizeTask.get();
        HashMap<String,Object> map = new HashMap<>();
        map.put("list", list);
        map.put("size", size);
        // 4.将结果返回给前端
        return ResultAjax.succ(map);
    }

}
